package com.openingedu.mba.screen.fragment;

import java.util.Date;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.gson.reflect.TypeToken;
import com.lurencun.android.support.widget.CommonAdapter;
import com.openingedu.mba.R;
import com.openingedu.mba.common.CommConsts;
import com.openingedu.mba.common.CommonUtil;
import com.openingedu.mba.entity.PaperVO;
import com.openingedu.mba.entity.QuestionVO;
import com.openingedu.mba.http.HttpHandler;
import com.openingedu.mba.persist.DataHelper;
import com.openingedu.mba.persist.DbOrder;
import com.openingedu.mba.persist.DbPaper;
import com.openingedu.mba.screen.adapter.ServerLogicAdapter;
import com.openingedu.mba.service.OrderService;
import com.openingedu.mba.service.PaperService;
import com.openingedu.mba.util.GsonUtil;

public class FragmentServerTabLogic extends SherlockFragment {

	private static final String TAG = FragmentServerTabLogic.class.getSimpleName();
	private Context mContext;
	private ListView listView;
	
	private CommonAdapter<PaperVO> logicAdapter;
	private List<PaperVO> paperList;
	private PaperService paperService;
	private OrderService orderService;
	private DataHelper dataHelper;
	private boolean initialized = false;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LinearLayout logicLayout = (LinearLayout) inflater.inflate(
				R.layout.ft_server_tab_logic, container, false);
		
		mContext = logicLayout.getContext();
		dataHelper = new DataHelper(mContext);
		listView = (ListView) logicLayout.findViewById(R.id.list_container);
		TextView emptyView = (TextView)logicLayout.findViewById(R.id.listEmptyView);
		listView.setEmptyView(emptyView);
		paperService = new PaperService();
		orderService = new OrderService();
		logicAdapter = new ServerLogicAdapter(mContext, adapterHandler);
		
		if (!initialized) {
			// 网络不可用
			if (!CommonUtil.isNetworkAvailable(mContext)) {
				
			} else {
				loadServerPapers();
				initialized = true;
			}
		} else {
			if (paperList != null) {
				logicAdapter.updateDataCache(paperList);
				listView.setAdapter(logicAdapter);
			} else {
				Log.i(TAG, "paper is empty.");
			}
		}
		return logicLayout;
	}

	// 接收adapter点击事件
	final Handler adapterHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				// 下载
				case 0:
					if (!CommonUtil.isNetworkAvailable(mContext)) {
						Toast.makeText(mContext,"网络不可用，请打开或检查网络设置。", Toast.LENGTH_SHORT).show();
					} else {
						PaperVO paper = (PaperVO) msg.obj;
						downloadPaper(paper);
					}
					break;
				// 购买
				case 1:
					if (!CommonUtil.isNetworkAvailable(mContext)) {
						Toast.makeText(mContext,"网络不可用，请打开或检查网络设置。", Toast.LENGTH_SHORT).show();
					} else {
						PaperVO paper = (PaperVO) msg.obj;
						// 请求服务器，取得订单号
						getOrderIDForPaper(paper);
					}
					break;
				default:
					break;
			}
		}
	};
	
	/**
	 * 处理server返回的试卷
	 * 
	 * @param obj
	 *            server返回的试卷字符串
	 */
	private void handlePaper(String obj) {
		try {
			Map<String, Object> map = GsonUtil.stm(obj);
			Integer result = GsonUtil.oti(map.get("Result"));
			// 操作成功
			if (result == 0) {
				Log.i(TAG, "locate paper success.");
				String papers = GsonUtil.otj(map.get("papers"));
				// 服务器返回的试卷列表
				paperList = GsonUtil.stl(papers,
						new TypeToken<List<PaperVO>>() {
						}.getType());
				
				// 取得本地的试卷列表
				if (dataHelper != null) {
					List<DbPaper> localPapers = dataHelper.getDbPaperDao().queryForAll();
					if (localPapers != null) {
						// 对比列表, 查看是否已经下载过该试卷
						for (PaperVO paperVO : paperList) {
							for (DbPaper dbPaper : localPapers) {
								if (paperVO.getPaperID() == dbPaper.getPaperID()) {
									paperVO.setDownloaded(true);
									break;
								}
							}
						}
					}
				}
				logicAdapter.updateDataCache(paperList);
				listView.setAdapter(logicAdapter);
			}
			// 操作失败
			else {
				Log.i(TAG, "locate paper success.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加载列表
	 */
	private void loadServerPapers() {
		paperService.loadLogicPaper(mContext, new HttpHandler(mContext, true) {

			@Override
			protected void success(String obj) {
				super.success(obj);
				Log.i(TAG, "server logic paper load success.");
				handlePaper(obj);
			}

			@Override
			protected void failure(String obj) {
				super.failure(obj);
				Log.i(TAG, "server logic paper load failure.obj=" + obj);
			}
		});
	}
	
	/**
	 * 购买会员
	 */
	private void getOrderIDForPaper(final PaperVO paper) {
		paperService.getOrderIDForPaper(mContext, new HttpHandler(mContext, true) {

			@Override
			protected void success(String obj) {
				super.success(obj);
				try {
					Map<String, Object> map = GsonUtil.stm(obj);
					Integer result = GsonUtil.oti(map.get("Result"));
					// 操作成功
					if (result == 0) {
						// TODO id of order
						Integer orderDID = GsonUtil.oti(map.get("orderDID"));
						String orderID = GsonUtil.ots(map.get("orderID"));
						buyPaper(paper, orderDID, orderID);
					}
					// 操作失败
					else {
						Log.d("------", "getOrderID failure. result=" + result);
					}
				} catch (Exception e) {
					Log.e("------", "getOrderID error.", e);
				}
			}
			
			@Override
			protected void failure(String obj) {
				super.failure(obj);
				Log.i(TAG, "server logic paper load failure.");
			}
		}, paper.getPaperID());
	}
	
	/**
	 * 下载试题
	 * @param paper
	 */
	private void downloadPaper(final PaperVO paper) {
		paperService.downloadPaper(mContext, new HttpHandler(mContext, true) {

			@Override
			protected void success(final String obj) {
				super.success(obj);
				new Handler().post(new Runnable() {
					
					@Override
					public void run() {
						handlePersistPaper(paper, obj);
					}
				});
			}
			
			@Override
			protected void failure(String obj) {
				super.failure(obj);
				Log.i(TAG, "download paper failure.");
			}
		}, paper.getPaperID());
	}
	
	private void handlePersistPaper(final PaperVO paper, final String paperObj) {
		try {
			Map<String, Object> map = GsonUtil.stm(paperObj);
			String questionString = GsonUtil.otj(map.get("questionList"));
			List<QuestionVO> questionList = GsonUtil.stl(questionString, new TypeToken<List<QuestionVO>>() {}.getType());
			// 保存试题
			boolean saveResult = paperService.persistPaper(mContext, dataHelper, paper, questionList);
			// 保存成功
			if (saveResult) {
				paper.setDownloaded(true);
				logicAdapter.updateDataCache(paperList);
				listView.setAdapter(logicAdapter);
			}
			else {
				Toast.makeText(mContext, "下载试题失败，请稍后重试。", Toast.LENGTH_LONG).show();
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(mContext, "下载试题发生异常，请稍后重试。", Toast.LENGTH_LONG).show();
		}
	}
	
//	public void switchToOrderList() {
////		String[] keys = new String[] { AppSetting.MENU_TITLE};
////		Object[] vals = new Object[] { "订单列表" };
////		ActivitySwitcher.switchTo(getSherlockActivity(), OrderListActivity.class, keys, vals);
//		MainActivity ra = (MainActivity) getActivity();
//		ra.getSlidingMenuFg().switchOrderFg();
//	}
	
	/**
	 * 调用有米支付购买试卷
	 * @param orderDID 
	 * @param 试卷订单号
	 */
	private void buyPaper(PaperVO paper, Integer orderDID, String orderID) {
		Log.i(TAG, "buyPaper orderID=" + orderID + ", orderDID=" + orderDID);
		DbOrder order = new DbOrder();
		order.setOrderID(orderID);
		order.setOrderDID(orderDID);
		order.setOrderPrice(paper.getPaperPrice());
		order.setOrderStatus(CommConsts.Order.NONE_PAID);
		order.setOrderTime(new Date());
		order.setPaperID(paper.getPaperID());
		order.setPaperTitle(paper.getPaperTitle());
		orderService.persistOrder(mContext, order);
		
		Toast.makeText(mContext, "订单已加入，请在[订单管理]中支付", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onResume() {
		super.onResume();
	}
	
	
}
